16. Exercise: Loops

Exercise: Loops

Using loops to iterate over an array

Task Description:

Loops are used to iterate over and process data. In the workspace below, you'll find a simple array of integers, like the ones we created a little while ago:

int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

To get some practice with the basic loop syntax in Java, try iterating over this array and printing out the values, like this:

1
2
3
4
5
6
7
8
9
10

See if you can get this same result with all three types of loops!

Task List:

Task Feedback:

Nice work!

Code

If you need a code on the https://github.com/udacity.

  • userCode:

    export PATH=/data/jdk-15.0.1/bin:$PATH
    export JAVA_HOME=/data/jdk-15.0.1/bin

  • Solution

    ND079 C1 L1 A12 Loop Exercise Solution

    Here's our code. Note that when iterating over the list, we start at 0 (since the index for the list starts at 0).

    public class LoopExercise {
    
        public static void main(String[] args) {
    
            int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    
            // Add for Loop Here
            for (int i = 0; i < numbers.length; i++) {
                System.out.println(numbers[i]);
            }
    
            // Add while Loop Here
            int index = 0;
            while (index < numbers.length) {
                System.out.println(numbers[index]);
                index++;
            }
    
            // Add Do while Loop Here
            int counter = 0;
            do {
                System.out.println(numbers[counter]);
                counter++;
            } while (counter < numbers.length);
    
        }
    
    }